package com.ydche.service.impl;

import com.ydche.dao.IInsQryDao;
import com.ydche.dao.IInsuranceDao;
import com.ydche.dao.ILocationDao;
import com.ydche.idl_output.*;
import com.ydche.service.ICarInfoService;
import com.ydche.service.ICustomerService;
import com.ydche.service.InsQryService;
import com.ydche.service.InsuranceService;
import com.ydche.util.MyTime;
import org.apache.thrift.TException;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class InsQryServiceImpl implements InsQryService {

    @Autowired
    private IInsQryDao insQryDao;

    @Autowired
    private ILocationDao locationDao;

    @Autowired
    private InsuranceService insuranceService;

    @Autowired
    private ICarInfoService carInfoService;

    @Autowired
    private ICustomerService customerService;

    @Override
    public void addInsQryLog(Long userId, QuoteParmBiz parm, AccurateQuoteResp quoteResult) {
        try {
            AccurateQuoteParm quoteParm = parm.getParm();
            InsuranceUnitInfo unitInfo = insuranceService.getInsuranceUnitInfo(quoteParm.getInsurerCode());
            Long customerId = customerService.saveCustomer(userId, quoteParm.getPersonInfo().getOwnerMobile(), quoteParm.getPersonInfo().getOwnerName(), quoteParm.getPersonInfo().getOwnerId());
            Long carId = carInfoService.saveCarProfile(userId, customerId, quoteParm.getCarInfo().getLicenseNo(), quoteParm.getCarInfo().getFrameNo(),
                    quoteParm.getCarInfo().getEngineNo(), quoteParm.getCarInfo().getRegisterDate(), Boolean.parseBoolean(quoteParm.getCarInfo().getIsTrans()),
                    quoteParm.getCarInfo().getTransDate(), quoteParm.getCarInfo().getBrandCode(), quoteParm.getCityCode());
            InsuranceQueryListDB insQry =getInsuranceQueryListDB(userId, customerId, carId,
                    Integer.parseInt(unitInfo.getInsuranceCorpId()), quoteParm.getCiBeginDate(), quoteParm.getBiBeginDate(), quoteParm.getApplicationID(),
                    quoteParm.getCityCode(), parm.getDistrictCode(), quoteParm.getCoverageList());
            String carshiptax = "0.00";
            List<CoverageInfo> coverageInfoList = quoteParm.getCoverageList();
            if(quoteResult !=null ){
                if(quoteResult.getState().equals("1")){
                    insQry.setStatus(Short.parseShort(quoteResult.state));
                    for (QuoteResult result : quoteResult.getData()) {
                        BigDecimal ciPremium = new BigDecimal(result.getCiPremium().equals("")?"0":result.getCiPremium()).setScale(2,BigDecimal.ROUND_HALF_UP);
                        BigDecimal biPremium = new BigDecimal(result.getBiPremium().equals("")?"0":result.getBiPremium()).setScale(2,BigDecimal.ROUND_HALF_UP);
                        BigDecimal carShipTax = new BigDecimal(result.getCarshipTax().equals("")?"0":result.getCarshipTax()).setScale(2,BigDecimal.ROUND_HALF_UP);
                        BigDecimal totalPremium = ciPremium.add(biPremium).add(carShipTax).setScale(2,BigDecimal.ROUND_HALF_UP);
                        carshiptax = carShipTax.toString();
                        insQry.setTotalCost(totalPremium.toString());
                        insQry.setBiProposalNo(result.getChannelCode());
                        insQry.setQryServiceNo(result.getThpBizID());
                        insQry.setBizId(result.getBizID());
                        insQry.setDiscount(result.getRebates());
                        insQry.setPackageType(getRiskContent(quoteParm.getCiBeginDate(), result.getCiPremium(),
                                totalPremium.toString(), result.getCoverageList()));
                        coverageInfoList = result.getCoverageList();
                        break;
                    }
                }else{
                    insQry.setErrorMsg(quoteResult.getMsg());
                }
            }
            Long qryId = insQryDao.addInsQry(insQry);
            if(qryId.longValue()>0){
                insQryDao.addInsQryCost(getInsQryCostList(qryId.intValue(), carshiptax, coverageInfoList));
            }

         } catch (TException e) {
            e.printStackTrace();
        }
    }

    @Override
    public InsuranceQueryListDB getInsQry(Long userId, String bizId, boolean status) {
        return null;
    }

    @Override
    public List<InsuranceQueryListDB> getInsQryList(Long userId) {
        return null;
    }


    public List<InsQryCostListDB> getInsQryCostList(int qryId, String carshiptax, List<CoverageInfo> coverageInfoList) throws TException {
        List<InsQryCostListDB> qrycostList = new ArrayList<>();
        for(CoverageInfo coverageInfo: coverageInfoList){
            InsuranceTypes type = insuranceService.getInsuranceType(coverageInfo.getCoverageCode());
            if(type !=null) {
                InsQryCostListDB cost = new InsQryCostListDB();
                cost.setInsCatId(type.getId());
                cost.setQueryId(qryId);
                cost.setCost(coverageInfo.getInsuredPremium());
                if (!coverageInfo.getInsuredAmount().equalsIgnoreCase("Y")) {
                    cost.setWarrantyCost(coverageInfo.getInsuredAmount());
                }
                qrycostList.add(cost);
            }
        }
        return qrycostList;
    }


    public String getRiskContent(String ciBeginDate, String carshiptax, String totalCost, List<CoverageInfo> coverageInfoList) throws TException {
        StringBuffer sb = new StringBuffer();
        if(!ciBeginDate.equals("")){
            sb.append("车船税/保费(¥"+(carshiptax.equals("")?"0.00":carshiptax)+"元),");
        }
        for(CoverageInfo coverageInfo: coverageInfoList){
            InsuranceTypes type = insuranceService.getInsuranceType(coverageInfo.getCoverageCode());
            String cost = coverageInfo.getInsuredPremium()==null?"0.00":coverageInfo.getInsuredPremium().equals("")?"0.00": coverageInfo.getInsuredPremium();
            String amount = "";
            if (!coverageInfo.getInsuredAmount().equalsIgnoreCase("Y")) {
                amount = coverageInfo.getInsuredAmount();
            }
            sb.append(type==null?"":type.getType_name()+amount+"/保费(¥"+cost+"元),");
        }
        sb.append("总保费合计"+totalCost+"元");
        return sb.toString();
    }

    public InsuranceQueryListDB getInsuranceQueryListDB(Long userId, Long customerId, Long carId,
                                                        int insUnitId, String ciBeginDate, String biBeginDate, String appId,
                                                        String cityCode, String districtCode, List<CoverageInfo> coverageInfoList)throws TException{
        InsuranceQueryListDB insQry = new InsuranceQueryListDB();
        insQry.setCarId(carId);
        insQry.setInsUnitId(insUnitId);
        insQry.setCustomerId(customerId);
        insQry.setUserId(userId);
        insQry.setPackageType(getRiskContent(ciBeginDate, "0.00", "0.00", coverageInfoList));
        insQry.setIsValid(false);
        insQry.setTotalCost("0.00");
        insQry.setCityId(locationDao.getCity(cityCode).getId());
        insQry.setDistrictId(locationDao.getDistrict(districtCode).getId());
        insQry.setQueryTime(MyTime.getCurrentDateTime());
        insQry.setBiProposalNo("");
        insQry.setCiProposalNo("");
        insQry.setCiBeginDate(ciBeginDate);
        insQry.setCiEndDate(MyTime.DateFormat(MyTime.addYear(MyTime.transToDate(ciBeginDate), 1)));
        insQry.setBiBeginDate(biBeginDate);
        insQry.setBiEndDate(MyTime.DateFormat(MyTime.addYear(MyTime.transToDate(biBeginDate), 1)));
        insQry.setQryServiceNo("");
        insQry.setBizId("");
        insQry.setSource(appId);
        insQry.setDiscount("0.00");
        insQry.setStatus((short)0);
        insQry.setErrorMsg("");
        return insQry;
    }
}
